package com.xiaoxin.experience.service.environment;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoxin.experience.api.environment.model.EnvironmentInfo;
import com.xiaoxin.experience.service.environment.entity.EnvironmentEntity;
import com.xiaoxin.experience.service.environment.mapper.EnvironmentMapper;
import com.xiaoxin.experience.util.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * @author xiaoxin
 */
@Service
public class EnvironmentService extends ServiceImpl<EnvironmentMapper, EnvironmentEntity>
{

    public EnvironmentInfo getConfig(String remoteIp)
    {
        if (StringUtil.isBlank(remoteIp))
        {
            return null;
        }
        EnvironmentEntity environmentEntity = baseMapper.selectById(remoteIp);
        if (Objects.nonNull(environmentEntity))
        {
            return environmentEntity.toInfo();
        }
        return null;
    }

    @Transactional(rollbackFor = Exception.class)
    public void setConfig(EnvironmentInfo environmentInfo)
    {
        if (Objects.isNull(environmentInfo) || StringUtil.isBlank(environmentInfo.getRemoteIp()))
        {
            return;
        }
        saveOrUpdate(new EnvironmentEntity(environmentInfo));
    }
}
